package cn.vc.content.service.article;

import cn.vc.content.entity.article.ArticleCollect;
import cn.vc.content.mapper.article.ArticleCollectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ArticleCollectService {
    private final ArticleCollectMapper articleCollectMapper;

    @Autowired
    public ArticleCollectService(ArticleCollectMapper articleCollectMapper) {
        this.articleCollectMapper = articleCollectMapper;
    }


    public boolean collect(Long id, Long userId) {
        ArticleCollect articleCollect = new ArticleCollect();
        articleCollect.setArticleId(id);
        articleCollect.setUserId(userId);
        try {
            articleCollectMapper.insert(articleCollect);
            return true;
        } catch (Exception e) {
            log.debug("已经收藏了："+userId+" -> "+id);
            this.noCollect(id, userId);
            return false;
        }
    }


    public int noCollect(Long id, Long userId) {
        LambdaQueryWrapper<ArticleCollect> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ArticleCollect::getArticleId, id).eq(ArticleCollect::getUserId, userId);
        ArticleCollect articleCollect = articleCollectMapper.selectOne(lqw);
        if (articleCollect == null) return -1;
        return articleCollectMapper.deleteById(articleCollect.getId());
    }
}
